<!-- 数据表格组件 -->
<template>
  <!-- 新建按钮 -->
  <v-btn class="mr-2" color="primary" @click="createitem">
    <v-icon>mdi-plus</v-icon>
    <span>新建</span>
  </v-btn>
  <v-btn color="red" class="my-4" :disabled="selected.length === 0" @click="handleBatchDelete">
    批量删除
  </v-btn>
  <v-spacer />

  <!-- 数据表格 -->
  <v-data-table
    :headers="headers"
    :items="items"
    :loading="loading"
    v-model="selected"
    loading-text="正在加载..."
    show-select
    no-data-text="暂无数据"
  >
    <template v-for="(slotRender, key) in slots" v-slot:[`item.${key}`]="{ item }" :key="key">
      <component :is="slotRender(item)" />
    </template>

    <!-- 操作列自定义渲染 -->
    <template v-slot:[`item.actions`]="{ item }">
      <!-- 查看按钮 -->
      <v-icon class="mr-2 cursor-pointer" color="primary" size="20" @click="viewitem(item)">
        mdi-eye
      </v-icon>

      <!-- 编辑按钮 -->
      <v-icon
        class="mr-2 cursor-pointer"
        color="primary"
        size="20"
        :disabled="editingId !== null && editingId === item.id"
        @click="updateItem(item)"
      >
        mdi-pencil
      </v-icon>

      <!-- 删除按钮 -->
      <template v-if="DeleteLoadingMap[item.id]">
        <v-progress-circular indeterminate size="20" color="primary" class="mr-1" />
      </template>
      <template v-else>
        <v-icon
          class="mr-2 cursor-pointer"
          color="error"
          size="20"
          :disabled="editingId !== null && editingId === item.id"
          @click="confirmDelete(item)"
        >
          mdi-delete
        </v-icon>
      </template>
    </template>
  </v-data-table>

  <!-- 删除确认对话框 -->
  <v-dialog v-model="deleteDialog" max-width="400">
    <v-card>
      <v-card-title>确认删除</v-card-title>
      <v-card-text>确认删除该项吗？</v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn
          color="primary"
          variant="text"
          @click="((deleteDialog = false), (DeleteLoadingMap[selectedItem.id] = false))"
          >取消</v-btn
        >
        <v-btn color="error" variant="text" @click="deleteitem">删除</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { useMessageStore } from '@/stores/MessageStore'
import { onMounted, ref, watch } from 'vue'

// 组件属性定义
const props = defineProps({
  // 表格列配置
  headers: {
    type: Array,
    required: true,
  },
  // API 接口对象，必须包含 fetch 和 delete 方法
  api: {
    type: Object,
    required: true,
    validator: (value) => typeof value.fetch === 'function' && typeof value.delete === 'function',
  },
  // 刷新触发器，当值变化时重新获取数据
  refreshTrigger: {
    type: Number,
    default: 0,
  },
  slots: {
    type: Object,
    default: () => ({}),
  },
})

// 定义组件事件
const emit = defineEmits(['edit', 'create', 'check'])

// 解构 API 方法
const { fetch, delete: deleteItem, deleteBatch } = props.api

// 监听刷新触发器变化
watch(
  () => props.refreshTrigger,
  () => {
    fetchData()
  },
)

// 响应式数据
const items = ref([]) // 表格数据
const loading = ref(false) // 加载状态
const editingId = ref(null) // 当前编辑项ID
const deleteDialog = ref(false) // 删除确认对话框状态
const selectedItem = ref(null) // 当前选中项
const DeleteLoadingMap = ref({}) // 删除加载状态映射
const selected = ref([])

/**
 * 获取表格数据
 */
const fetchData = async () => {
  loading.value = true
  try {
    const response = await fetch()
    items.value = response.data
  } finally {
    loading.value = false
  }
}

/**
 * 查看项目详情
 * @param {Object} item - 项目数据
 */
const viewitem = (item) => {
  emit('check', item)
}

/**
 * 创建新项目
 */
const createitem = () => {
  emit('create')
  fetchData()
}

/**
 * 确认删除项目
 * @param {Object} item - 要删除的项目
 */
const confirmDelete = (item) => {
  DeleteLoadingMap.value[item.id] = true
  selectedItem.value = item
  deleteDialog.value = true
}

/**
 * 执行删除操作
 */
const deleteitem = async () => {
  try {
    await deleteItem(selectedItem.value.id)
    fetchData()
  } catch (error) {
    console.error('Error deleting item:', error)
  } finally {
    DeleteLoadingMap.value[selectedItem.value.id] = false
    deleteDialog.value = false
  }
}

const handleBatchDelete = async () => {
  const ids = selected.value
  const response = await deleteBatch(ids)
  if (response.code === 0) {
    useMessageStore().trigger(response.message, 'error')
  } else {
    useMessageStore().trigger(response.message, 'success')
  }
  selected.value = []
  fetchData()
}

/**
 * 更新项目
 * @param {Object} item - 要更新的项目
 */
const updateItem = (item) => {
  emit('edit', item)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>
